package com.catbad.interceptor;

import com.catbad.annotations.Auth;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Set;

public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Set<String> auths = (Set<String>) session.getAttribute("auths");
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Auth auth = handlerMethod.getMethodAnnotation(Auth.class);
        if(auth==null) return true;
        if(auths!=null&&auths.contains(auth.value())){
            return true;
        }
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("没有足够的权限，请联系管理员");
        return false;
    }
}
